#include "comms.h"

namespace comms {

// cFile::Set
void cFile::Set(void *Src, const int Size, const char *FilePn) {
	m_Data.Set((char *)Src, Size);
	m_Pos = 0;
	m_FilePn = FilePn;
}

// cFile::Copy
void cFile::Copy(const void *Src, const int Size, const char *FilePn) {
	if(Size > 0 && Src != NULL) {
		m_Data.Copy((const char *)Src, Size);
	} else {
		m_Data.Clear();
	}
	m_Pos = 0;
	m_FilePn = FilePn;
}

// cFile::Clear
void cFile::Clear() {
	m_Data.Clear();
	m_Pos = 0;
	m_FilePn.Clear();
}

// cFile::Read
int cFile::Read(void *To, const int MaxSize) const {
	if(m_Pos >= m_Data.Count()) {
		return -1;
	}
	
	const int Size = cMath::Min(MaxSize, m_Data.Count() - m_Pos);
	memcpy(To, &m_Data[m_Pos], Size);
	m_Pos += Size;
	
	return Size;
}

// cFile::Write
void cFile::Write(const void *Fm, const int Size) {
	m_Data.InsertRange(m_Pos, (const char *)Fm, Size);
	m_Pos += Size;
}

//-----------------------------------------------------------------------------
// cFile::ReadString
//-----------------------------------------------------------------------------
bool cFile::ReadString(cStr *S, const char *Terminators) const {
	cAssert(S != NULL);
	cAssert(Terminators != NULL);
	
	cStr T;

	S->Clear();
	
	if(m_Pos >= m_Data.Count()) {
		return false;
	}

	T = Terminators;

	// Skip leading terminators
	while(m_Pos < m_Data.Count() && T.Contains(m_Data[m_Pos])) {
		m_Pos++;
	}
	
	// Read until terminator
	while(m_Pos < m_Data.Count() && !T.Contains(m_Data[m_Pos])) {
		S->Append(m_Data[m_Pos]);
		m_Pos++;
	}

	// Skip trailing terminators
	if(m_Pos < m_Data.Count() && T.Contains(m_Data[m_Pos])) {
		m_Pos++;
	}
	
	return true;
} // cFile::ReadString

// cFile::WriteString
void cFile::WriteString(const char *Str) {
	const int l = cStr::Length(Str);
	m_Data.InsertRange(m_Pos, Str, l); // w/o trailing zero.
	m_Pos += l;
}

} // comms